package com.gzyj.jtt808.v2013;

import com.gzyj.jtt808.utils.HexBytesUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;

import java.io.Serializable;

/**
 * @author lhj
 */

@Data
public class PackageHeader implements Serializable {

    private int msgId;//消息ID；
    private HeaderMsgBodyProperty msgBodyProperty;//消息体属性
    private String terminalPhoneNo;//终端手机号
    private Integer msgNum;//消息流水号

    private short ManualMsgNum;// 手动消息流水号（only test） 发送计数器 占用两个字节，为发送信息的序列号，用于接收方检测是否有信息的丢失，上级平台和下级平台接自己发送数据包的个数计数，互不影响。程序开始运行时等于零，发送第一帧数据时开始计数，到最大数后自动归零

    //消息包封装项
    private short packgeCount;//消息总包数
    private short packageIndex;//报序号 从1开始

    private static int internalMsgNo = 0;

    public PackageHeader() {
    }

    public PackageHeader(int msgId) {
        synchronized ((Integer) internalMsgNo) {
            if (internalMsgNo == Short.MAX_VALUE) {
                internalMsgNo = 0;
            }
        }

        this.msgId = msgId;
    }

    public ByteBuf encode() {
        ByteBuf buf = Unpooled.buffer(16);
        buf.writeShort(this.msgId);
        buf.writeBytes(this.msgBodyProperty.encode());
        buf.writeBytes(HexBytesUtil.WriteBCD(this.terminalPhoneNo, 12));
        if(this.msgNum==null){
            this.msgNum = ++internalMsgNo;
        }
        buf.writeShort(this.msgNum);
        if (this.msgBodyProperty.isSubcontract()) {
            buf.writeShort(this.packgeCount);
            buf.writeShort(this.packageIndex);

        }

        return buf;

    }

    public PackageHeader decode(ByteBuf buf) {
        byte[] temp = HexBytesUtil.readByOffset(buf, 2);
        this.msgId = Integer.parseInt(HexBytesUtil.bytesToHex(temp), 16);
        temp = HexBytesUtil.readByOffset(buf, 2);
        this.msgBodyProperty = new HeaderMsgBodyProperty();
        this.msgBodyProperty.decode(temp);


        temp = HexBytesUtil.readByOffset(buf, 6);


        this.terminalPhoneNo = HexBytesUtil.ReadBCD(temp, 12);

        this.msgNum = buf.readUnsignedShort();

        if (this.msgBodyProperty.isSubcontract()) {
            temp = HexBytesUtil.readByOffset(buf, 2);
            this.packgeCount = Short.parseShort(HexBytesUtil.bytesToHex(temp), 16);
            temp = HexBytesUtil.readByOffset(buf, 2);
            this.packageIndex = Short.parseShort(HexBytesUtil.bytesToHex(temp), 16);
        }


        return this;
    }

}